﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Tools.Utility;
using Dora.Tools.Utility.Const;
using Microsoft.Extensions.Logging;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 机构文档表服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class OrgDocService : DoraServiceBase, IOrgDocService
    {
        
        private ISugarUnitOfWork _unitOfWork;
        private readonly OrgDocRepository _repository;
        private readonly OrganizationRepository _organizationRepository;
        public OrgDocService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _repository = new OrgDocRepository(unitOfWork);
            _organizationRepository = new OrganizationRepository(unitOfWork);
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> Create(OrgDocEntity entity)
        {
            entity.CreatedTime = DateTime.Now;
            var result = await _repository.InsertAsync(entity);
            return ResultDto<int>.Success(result.Id);
        }


        /// <summary>
        /// 根据Id获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<OrgDocEntity> GetById(int id)
        {
            return await _repository.FirstOrDefaultAsync(id);
        }


        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrgDocViewDto>> GetPageList(OrgDocQueryDto input)
        {
            var page = await _repository.GetPageList(input);
            return page;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> Update(OrgDocEntity entity)
        {
            entity.UpdatedTime = DateTime.Now;
            var result= await _repository.UpdateAsync(entity);
            if (result)
            {
                return ResultDto<bool>.Success(true);
            }
            else
            {
                return ResultDto<bool>.Error("操作失败");
            }
        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<OrgDocEntity>> GetList(List<int> idList)
        {
            if (idList == null || idList.Count == 0)
            {
                return new List<OrgDocEntity>();
            }
            var list = await _repository.GetAllListAsync(it => idList.Contains(it.Id));
            return list;
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrgDocEntity>> GetAll()
        {
            var list = await _repository.GetAllListAsync();
            return list;
        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<OrgDocEntity>> GetListByTopOrgId(int topOrgId)
        {
            var list = await _repository.GetAllListAsync(it => it.TopOrgId == topOrgId && it.IsDeleted == 0);
            return list;
        }

        /// <summary>
        /// 复制文档到某个组织机构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> CopyToOrg(OrgDocCopyDto input)
        {
            if (input == null || input.DocIdList==null || input.DocIdList.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "没有需要复制的文档", 0);
            }
            var num = 0;
            var org =await _organizationRepository.FirstOrDefaultAsync(it => it.Id == input.OrgId);
            if (org == null)
            {
                return new ResultDto<int>(ResultCode.Fail, "组织机构不存在", 0);
            }
            var arrLevelPath = ConvertHelper.StringToList<int>(org.LevelPath, ',');
            if (arrLevelPath.Count < 1)
            {
                return new ResultDto<int>(ResultCode.Fail, "组织机构层级设置错误", 0);
            }
            var topOrgId = arrLevelPath[0];
            var existList = await GetListByTopOrgId(topOrgId);
            var needAddList = await GetList(input.DocIdList);
            var newList = new List<OrgDocEntity>();
            foreach (var item in needAddList)
            {
                var existItem = existList.Where(it => it.DocUrl.ToLower() == item.DocUrl.ToLower()).FirstOrDefault();
                if (existItem == null)
                {
                    item.Id = 0;
                    item.OrgId = org.Id;
                    item.TopOrgId = topOrgId;
                    item.CreatedTime = DateTime.Now;
                    item.CreatedUserId = input.OpUserId;
                    item.CreatedUserName = input.OpUserName;
                    item.UpdatedTime = DateTime.Now;
                    item.UpdatedUserId = input.OpUserId;
                    item.UpdatedUserName = input.OpUserName;
                    item.IsTop = 0;
                    item.TopTime = DateTime.Now;
                    newList.Add(item);
                }
            }
            if (newList.Count > 0)
            {
                num=await _repository.CreateRange(newList);
            }

            return ResultDto<int>.Success(num);
        }

        /// <summary>
        /// 一份文档创建在多个组织机构下
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> CreateInOrgs(OrgDocSaveDto input)
        {
            if (input == null || input.OrgIdList==null || input.OrgIdList?.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "没有需要复制的文档", 0);
            }
            var num = 0;
            var orgList = await _organizationRepository.GetAllListAsync(it => input.OrgIdList.Contains( it.Id ));
            if (orgList == null || orgList.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "组织机构不存在", 0);
            }

            var newList = new List<OrgDocEntity>();
            foreach (var itemOrg in orgList)
            {
                var arrLevelPath = ConvertHelper.StringToList<int>(itemOrg.LevelPath, ',');
                if (arrLevelPath.Count < 1)
                {
                    return new ResultDto<int>(ResultCode.Fail, "组织机构层级设置错误", 0);
                }
                var topOrgId = arrLevelPath[0];
                var item = new OrgDocEntity();
                item.Id = 0;
                item.TopOrgId = topOrgId;
                item.OrgId = itemOrg.Id;
                item.Type = (int)input.Type;
                item.Name = input.Name;
                item.DocExt = StringHelper.GetFileExt(input.DocUrl);
                item.DocUrl = input.DocUrl;
                item.PreviewUrl = "";
                item.Sort = 0;
                item.Remark = input.Remark;
                item.IsTop = 0;
                item.TopTime = DateTime.Now;
                item.CreatedTime = DateTime.Now;
                item.CreatedUserId = input.OpUserId;
                item.CreatedUserName = input.OpUserName;
                item.UpdatedTime = DateTime.Now;
                item.UpdatedUserId = input.OpUserId;
                item.UpdatedUserName = input.OpUserName;
                newList.Add(item);
            }

            if (newList.Count > 0)
            {
                num = await _repository.CreateRange(newList);
            }

            return ResultDto<int>.Success(num);
        }
    }
}
